<template>
  <div class="upLoad">
    <div style="padding: 20px 10px">
      <ul v-for="(items, index) in FJData" :key="index">
        <div style="line-height: 30px; border-bottom: 1px solid #d2d2d2; font-size: 17px">
          <li style="font-weight: 600" v-if="items.title">
            <span style="color: red;" v-show="isReadOnly&&items.isReadOnly">*</span>{{ items.title }}
          </li>
          <li style="font-size: 14px">
            文件：<span v-if="items.FileName.length == 0">暂无数据</span>
            <div v-else>
              <p style="color: #3f8ffc;" v-for="it in items.FileName">
                <span @click="handleLJD(it)">{{
                  it.FILENAME
                }} </span><van-icon @click="delectFile1(it)" name="close" color="red" style="float: right;" />
              </p>
            </div>

          </li>
          <van-uploader :disabled="disabled" :deletable="!ISDelete" @click-upload="getList(items)"
            @click-preview="lookFile" :after-read="afterRead" :before-delete="delectFile" v-model="items.fileList">
          </van-uploader>
        </div>
      </ul>
    </div>
  </div>
</template>


<script>
import {
  dataTransFile,
  dataTransFilePreview,
  FileServerProxy,
} from '@/utils/api'
import { uploadFile } from './api'
export default {
  data() {
    return {
      groupGuids: [],
      ROW_GUID: "",
      cityCode: "",
      tableBZCL: {
        FILENAME: "",
        FILETYPE: "",
        FILESIZE: "",
        CREATEUSERID: "",
        CREATEDATE: "",
        FILEGUID: "",
      },
    }
  },
  props: {
    disabled: Boolean,
    IsBZWJ: Boolean,
    typeParam: String,
    tkRowGuid: String,
    rowData: Object,//当前行的信息
    FJData: Array,//需要展示的内容
    SHITUID: String,//回显视图id
    UpLoadID: String,//上传视图id
    ISDelete: Boolean,
    CUNID: String,
    isoutFile: Boolean,//主要是施工巡查 等其他的Eca服务 省级账号没有权限 需要获取当前案卷的citycode1
    isReadOnly: {
      type: Boolean,
      default: true,
    }
  },
  methods: {
    getList(item) {
      this.groupGuids = item.groupGuid
    },
    //必填项判断
    bitian1(){
      let index = 0
      this.FJData.forEach((item,index1)=>{
        console.log(item.title)
        if(this.isReadOnly&&item.isReadOnly&&item.fileList.length == 0){
          console.log(item.title)
          index+=1
        }
      })
      if(index>0){
        //提示还有必填项未填写
      } else{
        //可以提交
      }
      return index
    },
    //获取补正文件
    getFileBZGZ: async function () {
      debugger
      let me = this
      let params = {
        accessCode: '688bd3883572440a859dfd8ba9194e7b',
        cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '',
        params: {
          dataguid: '105bb93b-682d-42db-adeb-49d2c40e269e',
          searchObject: JSON.stringify([
            { field: 'TO_ROW_GUID', value: me.ROW_GUID, operator: '=' },
          ])
        }
      }
      const res = await FileServerProxy(params)
      if (JSON.parse(res.data.data) && JSON.parse(res.data.data).Data.length > 0) {
        JSON.parse(res.data.data).Data.forEach((element) => {
          this.FJData.forEach((item) => {
            if (item.groupGuid == "123") {
              element['file'] = {
                name: element.FILENAME,
              }

              this.getFileUrl(element, item)

            }
          })
        })
      }
    },
    //获取相关材料
    getFile1: async function () {
      let me = this
      let groupGuid = []
      this.FJData.forEach((item) => {
        groupGuid.push(item.groupGuid)
      })
      if (me.isoutFile) {
        me.cityCode = me.rowData.CITY
      } else {
        me.cityCode = window.localStorage.getItem('isGJM') == 'true' ? window.localStorage.getItem("citycode") : window.localStorage.getItem("citycodeChange")
      }
      let params = {
        accessCode: '1fdcbce42c6d4748a020feba618d54b8',
        cityCode: me.cityCode,
        params: {
          groupGuid: groupGuid.join(','),
          toRowGuid: this.ROW_GUID,//me.rowData.ROW_GUID,
          token: window.localStorage.getItem('token'),
        },
      }
      //如果是村公示 使用me.CUNID
      console.log(this.FJData, 'this.groupGuids')
      try {
        if (this.FJData[0].title == '公示回执') {
          params.params.toRowGuid = me.CUNID
        }
      } catch (err) {

      }
      const res1 = await FileServerProxy(params)
      let ress = JSON.parse(res1.data.data)
      if (ress.FilesInfo && ress.FilesInfo.length > 0) {
        ress.FilesInfo.forEach((element) => {
          this.FJData.forEach((item) => {
            if (element.GROUPGUID == item.groupGuid) {
              element['file'] = {
                name: element.FILENAME,
              }

              this.getFileUrl(element, item)

            }
          })
        })
      }
    },
    //获取附件文件流
    getFileUrl: async function (element, item) {
      var fileGuids = "";
      if (this.IsBZWJ) {
        fileGuids = element.FILEGUID;
      } else {
        fileGuids = element.ROW_GUID;
      }
      if (this.isoutFile) {
        this.cityCode = this.rowData.CITY
      } else {
        this.cityCode = window.localStorage.getItem('isGJM') == 'true' ? window.localStorage.getItem("citycode") : window.localStorage.getItem("citycodeChange")
      }
      let formData = new FormData()
      formData.append('accessCode', this.SHITUID)
      formData.append(
        'cityCode', this.cityCode
      )
      formData.append(
        'paramStr',
        JSON.stringify({
          fileGuid: fileGuids,
        })
      )
      let response = await dataTransFilePreview(formData)
      if (response) {
        var img = new Blob([new Int8Array(response.data, 0)], {
          type: response.headers['content-type'],
        }) //type类型可自定义
        element['isImage'] = true
        element['url'] = window.URL.createObjectURL(img)
        //生成的url只能访问一次
        if (element.FILETYPE == '.pdf') {
          item.FileName.push(element)
        } else {
          item.fileList.push(element)
        }
        this.$emit("getFileServerUpload1", item);
      }
    },
    //相关材料
    afterRead(file) {
      file.status = 'uploading';
      file.message = '上传中...';
      // 此时可以自行将文件上传至服务器
      this.getFileServerUpload(file.file, file)
    },
    delectFile: async function (file) {
      debugger
      let fileguid = ''
      if (file.ROW_GUID) {
        fileguid = file.ROW_GUID
      } else {
        fileguid = this.fileGuid
      }
      if (this.isoutFile) {
        this.cityCode = this.rowData.CITY
      } else {
        this.cityCode = window.localStorage.getItem('isGJM') == 'true' ? window.localStorage.getItem("citycode") : window.localStorage.getItem("citycodeChange")
      }
      if (fileguid) {
        let params = {
          accessCode: 'ce9b691634de4ebca68dc5bb638d07f4',
          cityCode: this.cityCode,
          params: {
            fileGuid: fileguid,
            token: window.localStorage.getItem('token'),
          },
        }
        const res = await FileServerProxy(params)
        let data = JSON.parse(res.data.data).Success
        if (data) {
          this.$emit("delectFile", true);
          this.$toast.success('删除成功!')
          if (this.IsBZWJ) {
            //删除补正文件
            this.deleteBZWJ(file);
          }
        }
      }
      return false;
    },
    deleteBZWJ: async function (item) {
      var p = {
        PKID: item.AFFIXID,
        ROW_GUID: item.ROW_GUID
      }
      let params3 = {
        accessCode: '434b72c2945518775ee423268b0b8121',
        cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '',
        params: {
          dataGuid: '105bb93b-682d-42db-adeb-49d2c40e269e',
          strParams: JSON.stringify([this.tableBZCL]),
          token: window.localStorage.getItem('token')
        }
      }
      const res3 = await FileServerProxy(params3);
    },
    delectFile1: async function (file) {
      debugger
      if (this.ISDelete) {
        this.$toast.fail('该用户暂不支持删除')
        return false
      }
      let fileguid = ''
      if (file.ROW_GUID) {
        fileguid = file.ROW_GUID
      } else {
        fileguid = this.fileGuid
      }
      if (fileguid) {
        let params = {
          accessCode: 'ce9b691634de4ebca68dc5bb638d07f4',
          cityCode: window.localStorage.getItem('isGJM') == 'true' ? window.localStorage.getItem("citycode") : window.localStorage.getItem("citycodeChange"),
          params: {
            fileGuid: fileguid,
            token: window.localStorage.getItem('token'),
          },
        }
        const res = await FileServerProxy(params)
        let data = JSON.parse(res.data.data).Success
        if (data) {
          this.$toast.success('删除成功!')
          this.$emit("delectFile", true);
          //删除this.FJData当前行数据
          this.FJData.forEach((item, index1) => {
            item.FileName.forEach((it, index) => {
              if (it.ROW_GUID == fileguid) {
                item.FileName.splice(index, 1)
              }
            })
          })
        }
      }

    },
    lookFile(item) {
      if (item.isImage == false) {
        if (ZWJSBridge) {
          ZWJSBridge.openLink({
            url: item.url,
          })
            .then((res) => { })
            .catch((err) => { })
        }
      }
    },
    getFileServerUpload: async function (file, data3) {
      debugger
      console.log(file, 'file')
      let data = {
        toRowGuid: this.ROW_GUID,
        groupGuid: this.groupGuids,
        token: window.localStorage.getItem('token'),
      }
      //如果是村公示 使用me.CUNID
      console.log(this.groupGuids, 'this.groupGuids')
      if (this.groupGuids.FileName == '村公示') {
        params.params.toRowGuid = this.CUNID
      }
      if (this.isoutFile) {
        this.cityCode = this.rowData.CITY
      } else {
        this.cityCode = window.localStorage.getItem('isGJM') == 'true' ? window.localStorage.getItem("citycode") : window.localStorage.getItem("citycodeChange")
      }
      let formData = new FormData()
      formData.append('file', file)
      formData.append('accessCode', this.UpLoadID)
      formData.append(
        'cityCode', this.cityCode

      )
      formData.append('token', window.localStorage.getItem('token'))
      formData.append('paramStr', JSON.stringify(data))
      const res = await dataTransFile(formData)
      try {
        let data1 = JSON.parse(res.data.data).FileList
        if (this.IsBZWJ) {
          //上传补正材料
          this.tableBZCL.FILENAME = data1[0].FILENAME;
          // this.tableBZCL.FIFILETYPE=daya1.FILETYPE;
          //this.tableBZCL.FILESIZE=data1.FILESIZE;
          this.tableBZCL.CREATEUSERID = 1;
          this.tableBZCL.CREATEDATE = this.getNowTime().split(' ')[0];
          this.tableBZCL.FILEGUID = data1[0].FILEGUID;
          this.fileGuid = data1[0].FILEGUID
          //判断是pdf还是照片
          if (data1[0].FILEGUID) {
            data3.status = 'done';
            data3.message = '';
            this.$emit("getFileServerUpload", data1);
            this.$toast.success('上传成功!')
          } else {
            data3.status = 'failed';
            data3.message = '上传失败';
            this.$toast.success('上传失败!')
          }
          this.saveBZCLInfo();
        } else {
          this.fileGuid = data1[0].FILEGUID
          //判断是pdf还是照片
          if (data1[0].FILEGUID) {
            data3.status = 'done';
            data3.ROW_GUID = this.fileGuid
            data3.message = '';
            this.$emit("getFileServerUpload", data1);
            this.$toast.success('上传成功!')
          } else {
            data3.status = 'failed';
            data3.message = '上传失败';
            this.$toast.success('上传失败!')
          }
        }

      } catch (err) {
        data3.status = 'failed';
        data3.message = '上传失败';
        this.$toast.fail('上传失败')
      }
    },
    handleLJD(data) {
      if (data.url == '') {
        this.$toast.fail('暂无数据')
      }
      else {
        // if (ZWJSBridge) {
        //   this.$toast.fail('暂不支持预览')
        // } else {
        const link = document.createElement('a')
        const evt = document.createEvent('HTMLEvents')
        evt.initEvent('click', false, false)
        link.href = data.url
        link.target = '_blank'
        link.style.display = 'none'
        document.body.appendChild(link)
        link.click()
        window.URL.revokeObjectURL(link.href)
        // }
      }
    },
    getNowTime: function () {
      let dateTime
      let yy = new Date().getFullYear()
      let mm = new Date().getMonth() + 1 < 10 ? '0' + (new Date().getMonth() + 1) : new Date().getMonth() + 1
      let dd = new Date().getDate() < 10 ? '0' + new Date().getDate() : new Date().getDate()
      let hh = new Date().getHours()
      let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
      let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
      dateTime = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss
      return dateTime
    },
    //保存补正材料
    async saveBZCLInfo() {
      this.tableBZCL.TO_ROW_GUID = this.ROW_GUID;
      this.tableBZCL.REMARK = '踏勘上传';
      let params3 = {
        accessCode: '0fb3f6123d1b4fe6851c99532c463f6f',
        cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '',
        params: {
          dataGuid: '105bb93b-682d-42db-adeb-49d2c40e269e',
          strParams: JSON.stringify([this.tableBZCL]),
          token: window.localStorage.getItem('token')
        }
      }
      const res3 = await FileServerProxy(params3);
    },
  },
  created() {
    if (this.typeParam) {
      this.ROW_GUID = this.tkRowGuid;
    } else {
      console.log(this.rowData.ROW_GUID, 'rowData')
      this.ROW_GUID = this.rowData.ROW_GUID;
    }
    if (this.IsBZWJ) {
      this.getFileBZGZ()
    } else {
      this.getFile1()
    }
    // if(this.isoutFile){
    //   cityCode=
    // }else{
    //   cityCode=
    // }

  }
}
</script>

<style scoped lang="scss"></style>
